import { Game } from '@/types/game';
import { ceil, floor } from 'lodash';

export function getGamePersonIds(game: Game) {
  return [game.eastPerson, game.southPerson, game.westPerson, game.northPerson];
}

export function getGameTotalPoints(game: Game) {
  const roundInfos = game.roundInfos;
  // 最终得点
  const finalPoints = [0, 25000, 25000, 25000, 25000];
  const positionPersonIds = getGamePersonIds(game);
  for (const roundInfo of roundInfos) {
    const { changePoints, huPersonId } = roundInfo;
    finalPoints[0] += changePoints[0];
    finalPoints[1] += changePoints[1];
    finalPoints[2] += changePoints[2];
    finalPoints[3] += changePoints[3];
    finalPoints[4] += changePoints[4];
    if (huPersonId) {
      const huPersonIndex = positionPersonIds.indexOf(huPersonId);
      finalPoints[huPersonIndex + 1] += finalPoints[0];
      finalPoints[0] = 0;
    }
  }
  return finalPoints;
}

export function getGameResultScores(game: Game) {
  const finalPoints = getGameTotalPoints(game);
  // 获取最大点数所在位置
  let maxPointNum = 0;
  let maxPointIndex = 0;
  for (let i = 1; i < finalPoints.length; i++) {
    if (finalPoints[i] > maxPointNum) {
      maxPointIndex = i;
      maxPointNum = finalPoints[i];
    }
  }
  // 计算计分点数
  const scorePoints = [];
  for (let i = 1; i < finalPoints.length; i++) {
    scorePoints[i] = finalPoints[i] - 30000;
    if (i === maxPointIndex) {
      scorePoints[i] = scorePoints[i] + 20000 + finalPoints[0];
    }
  }
  // 计算最终得分
  const scores = [];
  for (let i = 1; i < scorePoints.length; i++) {
    if (scorePoints[i] >= 0) {
      scores[i] = ceil(scorePoints[i] / 1000);
    } else {
      scores[i] = floor(scorePoints[i] / 1000);
    }
  }
  return scores;
}

export function getMergeGamesScores(games: Game[]) {
  const result: { [key: string]: number } = {};
  games.forEach(game => {
    const personIds = getGamePersonIds(game);
    const scores = getGameResultScores(game);
    personIds.forEach((id, index) => {
      if (id) {
        result[id] = (result[id] || 0) + scores[index + 1];
      }
    });
  });

  return result;
}
